package com.lzyjkz.quick_admin.web.controller.system;

import com.lzyjkz.quick_components.entity.Response;
import com.lzyjkz.quick_system.enums.machine.CPUWarnValueEnum;
import com.lzyjkz.quick_system.enums.machine.WarnLevelEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/system")
@RequiredArgsConstructor
@Slf4j
public class SystemController {
    private final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    private final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    @GetMapping("CPU")
    public Response<Map<String, Object>> CPU() {
        Map<String, Object> ans = new HashMap<>();

        // 获取CPU使用率
        double systemLoadAverage = operatingSystemMXBean.getSystemLoadAverage();
        ans.put("CPU_USAGE", systemLoadAverage);

        // 获取CPU使用率预警阈值级别
        CPUWarnValueEnum levelByValue = CPUWarnValueEnum.getLevelByValue(systemLoadAverage);
        ans.put("CPU_WARNING", levelByValue);

        // 获取警告级别
        assert levelByValue != null;
        ans.put("WARING_INFO", WarnLevelEnum.getByCode(levelByValue.getCode()));
        log.info("CPU: {}", ans);

        return Response.success(ans);
    }

    @GetMapping("JVM")
    public Response<Map<String, Object>> JVM() {
        Map<String, Object> ans = new HashMap<>();

        // 获取JVM启动时间
        long startTime = runtimeMXBean.getStartTime();
        ans.put("JVM_START_TIME", startTime);

        // 获取JVM运行时间
        long uptime = runtimeMXBean.getUptime();
        ans.put("JVM_RUN_TIME", uptime);

        // 获取JVM最大内存
//        long maxMemory = runtimeMXBean.get();
//        ans.put("JVM_MAX_MEMORY", maxMemory);

        return Response.success(ans);
    }


}
